package com.zxj.shop.admin.controller;

import cn.hutool.core.date.DateUtil;
import com.zxj.shop.admin.shiro.vo.ResultVO;
import com.zxj.shop.admin.utils.CosUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Api(tags = "文件上传")
@Controller
@RequiredArgsConstructor
@RequestMapping("/api/entry/file")
public class FileApiController {

    Logger logger = LoggerFactory.getLogger(FileApiController.class);

    private final CosUtil cosUtil;

    /**
     * 上传文件并返回对应url
     */
    @ApiImplicitParam(name = "file",value = "文件",required = true)
    @ApiOperation(value = "上传文件并返回对应url")
    @PostMapping("/upload")
    @ResponseBody
    public ResultVO upload(@RequestParam("file") MultipartFile file) {
        List<String> urls = new ArrayList<>();
        if (file != null) {
            try {
                String format = DateUtil.format(new Date(), "yyyyMMddHHmmss");
                String year = DateUtil.format(new Date(), "yyyyMM");
                // 获取源文件名称
                String originalFilename = file.getOriginalFilename();

                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String fileName = year + "/" + fileType + "/" + format + "." + fileType;
                cosUtil.putObject(file.getBytes(),fileName);
                urls.add(fileName);
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        return ResultVO.success(urls,"上传完成");
    }

}
